package com.changdiantech.cdfootball.plugins;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.king.app.updater.AppUpdater;
import com.king.app.updater.callback.UpdateCallback;

import java.io.File;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * UpdateVersionPlugin
 */
public class UpdateVersionPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler {

    private static String TAG = "MY_UPDATE";
    private static String CHANNEL_NAME = "plugins.football.com/update_version";
    private static Context context;
    private AppUpdater update;
    private MethodChannel eventChannel;

    private void openInstallPage(Context context, Uri apkUri) {
        Intent intent = new Intent();
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        System.out.println("UpdateVersionPlugin===onAttachedToEngine");
        context = binding.getApplicationContext();
        eventChannel = new MethodChannel(binding.getBinaryMessenger(), CHANNEL_NAME);
        eventChannel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        System.out.println("UpdateVersionPlugin===onDetachedFromEngine");

        if (update != null) {
            update.stop();
        }
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        Object object = call.arguments;
        System.out.println("UpdateVersionPlugin===onMethodCall===" + object);
        if (object.toString().length() < 5) {
            result.error(TAG, "URL错误", object);
            return;
        }
        if (!object.toString().startsWith("http")) {
            result.error(TAG, "URL错误", object);
            return;
        }
        update = new AppUpdater(context, object.toString()).setUpdateCallback(new UpdateCallback() {

            @Override
            public void onDownloading(boolean isDownloading) {
                System.out.println("UpdateVersionPlugin===onDownloading");
            }

            @Override
            public void onStart(String url) {
                System.out.println("UpdateVersionPlugin===onStart");
            }

            @Override
            public void onProgress(long progress, long total, boolean isChange) {
                System.out.println("UpdateVersionPlugin===onProgress---$progress");
            }

            @Override
            public void onFinish(File file) {
                System.out.println("UpdateVersionPlugin===onFinish==" + file);
                if (file.getName().endsWith(".apk")) {
                    Uri uri;
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        uri = Uri.fromFile(file);
                    } else {
                        String authority = context.getPackageName();
                        uri = FileProvider.getUriForFile(context, authority, file);
                    }
                    openInstallPage(context, uri);
                }
            }

            @Override
            public void onError(Exception e) {
                System.out.println("UpdateVersionPlugin===onError==" + e.getMessage());
            }

            @Override
            public void onCancel() {
                System.out.println("UpdateVersionPlugin===onCancel==");
            }
        });
        update.start();
    }
}
